import { LoginUser } from '@/models/LoginUser';
import { b64_decode, b64_encode } from '@/utils/codeUtils';
import type { CaseReducer, PayloadAction, SliceSelectors } from '@reduxjs/toolkit';
import { createSlice } from '@reduxjs/toolkit';

const LOGINUSERSTOREKEY = 'embedBossLoginUser';

export const loginUserSlice = createSlice<
  LoginUser,
  {
    updateLoginUser: CaseReducer<LoginUser, PayloadAction<LoginUser | undefined>>;
  },
  'loginUser',
  SliceSelectors<LoginUser>
>({
  name: 'loginUser',
  initialState: () => {
    const initialState = new LoginUser();
    const loginUserSecret = localStorage.getItem(LOGINUSERSTOREKEY);
    if (loginUserSecret) {
      try {
        Object.assign(initialState, JSON.parse(b64_decode(loginUserSecret)));
      } catch (err) {
        console.log('--loginUserSlice--loginUser--err--:', err);
      }
    }
    return initialState;
  },
  reducers: {
    updateLoginUser: (state, { payload = new LoginUser() }) => {
      localStorage.setItem(LOGINUSERSTOREKEY, b64_encode(JSON.stringify(payload)));
      return { ...payload };
    },
  },
});
